<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="../js/vue.js"></script>
  <script src="../js/rx.router.js"></script>
  <title>基础用法</title>
</head>

<body>
  <a href="../">返回目录</a>
  <div>
    onBeforeExit：退出系统之前的判断 <br>
    onBeforeChange：路由变更之前
  </div>
  <div id="app">

  </div>
</body>
<script>
  var menus = {
    pagename: 'app',
    component: getComponent('首页'),
    children: [{
        name: '页面1',
        pagename: 'page1',
        component: getComponent('页面1')
      },
      {
        name: '进不去的页面1。链接进入',
        pagename: 'page2',
        component: getComponent('页面2'),
      },
      {
        name: '页面3',
        pagename: 'page3',
        component: getComponent('页面3'),
        children: [{
            name: '页面3-子页面1',
            pagename: 'page3page1',
            component:{
              template:`<div><button @click="goTo">goTo预检查，注意地址栏</button></div>`,
              methods:{
                goTo(){
                  //预检查
                  this.$rxRouter.goTo('page3page2');
                }
              }
            }
          },
          {
            name: '进不去的页面2。(goTo进入 预检查)',
            pagename: 'page3page2',
            component: getComponent('页面3-子页面2'),
          }
        ]
      }
    ]
  }

  function getComponent(name) {
    return {
      template: `<div>
        <div>
          <strong>${name}</strong>
          <ul>
            <li v-for="item in $rxRouterInfo.menus" :key="item.pagename" :class="{
              active:$rxRouterInfo.current.pagename===item.pagename
            }"><a :href="'#'+item.path">{{item.name}}</a></li>
          </ul>
        </div>
        <component v-for="item in $rxRouterInfo.pages" :is="item.pagename" :key="item.pagename" v-show="$rxRouterInfo.current.pagename===item.pagename" />
      </div>`
    }
  }
  Vue.prototype.$rxRouter.init(menus, {
    //界面变化之前的检查
    onBeforeChange(toPagenames){
      if(toPagenames.indexOf('page2')!==-1||toPagenames.indexOf('page3page2')!==-1){
        return false;
      }
      return true;
    },
    //登录才要搞这些，没登录没意义
    onCancelBeforeExit() {
      //当onBeforeExit 被触发，又进行了forward 时触发
      console.log('取消退出了。');
    },
    onBeforeExit: function () {
      var resolve,
        reject,
        promise = new Promise((res, rej) => {
          resolve = res;
          reject = rej;
        });
      setTimeout(() => {
        if (confirm('是否退出系统?')) {
          resolve()
        } else {
          reject()
        }
      }, 1000)
      return promise
    }
  })
  new Vue({
    el: '#app',
    template: '<app/>',
    components: {
      app: menus.component
    }
  })

</script>

</html>
